package com.fr.hiram;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.fr.base.FRContext;

public class RemoteDatasourseAuthorityManager {
	private final static String XML_VERSION="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

	private static Map<String ,String> users=new HashMap<String,String>();
	private static Map<String,String> datasourses=new HashMap<String,String>();
	static{
		try {
			init();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		try {
			if(isAuthenticated("test", "test")){
				System.out.println(getDatasourse("test"));
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static InputStream getDatasourse(String name){
		String datasourse =datasourses.get(name);
		return new ByteArrayInputStream(datasourse.getBytes());
	}
	public static boolean  isAuthenticated(String name,String password){
		String p=users.get(name);
		if(!password.equals(p)){
			return false;
		}else{
			return true;
		}
	}
	private static void init() throws Exception{
//		FRContext.setCurrentEnv(new LocalEnv("G:\\FineReport\\FineReport_7.0.3\\WebReport\\WEB-INF"));
		InputStream in=FRContext.getCurrentEnv().readResource("authorityDatasourse.xml");
		SAXReader reader = new SAXReader();
	       Document document = reader.read(in);
	       Element root=document.getRootElement();
	       for ( Iterator i = root.elementIterator("User"); i.hasNext(); ) {
	           Element user = (Element) i.next();
	           String username=user.element("Username").getStringValue();
	          String password=user.element("Password").getStringValue();
	          String datasourceManageruserXML=user.element("DatasourceManager").asXML();
	          users.put(username, password);
	          datasourses.put(username, XML_VERSION+datasourceManageruserXML);
	        }
	}
	
}
